package com.kaikeba.estack.common.jdbc;

import com.kaikeba.estack.exception.DataAccessException;
import com.kaikeba.estack.common.util.BeanUtil;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 单一数据的结果集映射
 *
 * @Auth xingwan
 * @Date 2020/9/9 23:05
 **/
public class SingleColumnRowMapper<T> implements RowMapper<T> {

    /**
     * 缓存class对应的mapper
     */
    private static final Map<Class<?>, SingleColumnRowMapper<?>> FACTORY = new ConcurrentHashMap<>();

    private final Class<T> tClass;

    public SingleColumnRowMapper(Class<T> tClass) {
        this.tClass = tClass;
    }

    @Override
    public T mapRow(ResultSet resultSet, long rowNum) throws SQLException {
        ResultSetMetaData rsMeta = resultSet.getMetaData();
        int size = rsMeta.getColumnCount();
        if (size > 1) {
            throw new DataAccessException("返回的结果集列数大于1列");
        }
        return BeanUtil.convert(resultSet.getObject(1), tClass);
    }

    public static <T> SingleColumnRowMapper<T> getInstance(Class<T> tClass) {
        return (SingleColumnRowMapper<T>) FACTORY.computeIfAbsent(tClass, SingleColumnRowMapper::new);
    }

}
